from PySide6.QtWidgets import (QApplication,
    QDialog, QVBoxLayout, QLabel, QLineEdit, 
    QComboBox, QPushButton, QMessageBox
)
import sys
from Main_Window import MainWindow
class LoginDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("统一多域认证系统登录")
        self.setFixedSize(300, 200)
        
        # 角色选择
        self.role_combo = QComboBox()
        self.role_combo.addItems(["车载终端用户", "域管理员", "系统审计员"])
        
        # 凭证输入
        self.username_input = QLineEdit(placeholderText="用户名/设备ID")
        self.password_input = QLineEdit(placeholderText="密码/认证码", echoMode=QLineEdit.Password)
        
        # 登录按钮
        login_btn = QPushButton("登录", clicked=self.authenticate)
        
        # 布局
        layout = QVBoxLayout()
        layout.addWidget(QLabel("选择角色:"))
        layout.addWidget(self.role_combo)
        layout.addWidget(QLabel("用户标识:"))
        layout.addWidget(self.username_input)
        layout.addWidget(QLabel("认证凭证:"))
        layout.addWidget(self.password_input)
        layout.addWidget(login_btn)
        self.setLayout(layout)
        
        self.user_role = None  # 保存登录成功后的角色信息
        self.username = None  # 保存登录成功后的用户名

    def authenticate(self):
        """根据角色调用不同的认证方法"""
        role = self.role_combo.currentText()
        identifier = self.username_input.text()
        credential = self.password_input.text()
        
        try:
            if role == "车载终端用户":
                # 调用国密证书认证
                if not self._validate_vehicle(identifier, credential):
                    raise ValueError("设备证书验证失败")
            elif role == "域管理员":
                # 数据库验证管理员账户
                if not self._validate_admin(identifier, credential):
                    raise ValueError("管理员账号或密码错误")
            elif role == "系统审计员":
                # 双因素认证
                if not self._validate_auditor(identifier, credential):
                    raise ValueError("动态验证码无效")
            
            self.user_role = role
            self.username = identifier
            self.accept()  # 关闭对话框并返回QDialog.Accepted
            
        except Exception as e:
            QMessageBox.critical(self, "登录失败", str(e))

    def _validate_vehicle(self, device_id, cert_code):
        """模拟车载终端认证（实际需集成HSM）"""
        # 这里应调用硬件安全模块验证设备证书
        #return device_id.startswith("VEH_") and len(cert_code) == 16
        return True

    def _validate_admin(self, username, password):
        """模拟域管理员认证"""
        return username == "admin" and password == "admin"

    def _validate_auditor(self, user_id, otp):
        """模拟审计员双因素认证"""
        # 实际应调用OTP服务验证
        return user_id == "sj" and otp == "sj"
    

if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 显示登录窗口
    login_dialog = LoginDialog()
    if login_dialog.exec() == QDialog.Accepted:
        # 根据角色初始化主界面
        main_window = MainWindow(login_dialog.user_role,login_dialog.username)
        main_window.show()
        sys.exit(app.exec())
    else:
        sys.exit(0)